
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ListeningService implements Runnable {

    private boolean stop = false;
    public int portNum;
    DatagramSocket listeningSocket;
    ReqPro rp = new ReqPro();

    public ListeningService() throws UnknownHostException {
        this.setupSocket();
    }

    public void stopListening() {
        this.stop = true;
    }

    private void setupSocket() throws UnknownHostException {
        this.portNum = (int) (Math.random() * 9999) + 1000;
        if ((portNum > 9999) && (portNum < 1000)) {
            this.setupSocket();
        }

        try {
            this.listeningSocket = new DatagramSocket(this.portNum,
                    InetAddress.getLocalHost());
        } catch (SocketException e) {
            System.out.println("Port: " + portNum
                    + " already taken, trying one more");
            setupSocket();
        }
        System.out.println("Listening on PORT: " + portNum);
    }

    @Override
    public void run() {
        try {
            System.out.println("My IP: " + InetAddress.getLocalHost());
        } catch (UnknownHostException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        while (!stop) {
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData,
                    receiveData.length);
            try {
                listeningSocket.receive(receivePacket);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            String receivedMsg = new String(receivePacket.getData());
            if (receivedMsg.trim().toUpperCase().contains(PeerData.ACKNOWLEDGE)) {
                System.out.println(receivedMsg);
            } else {
                System.out.println("RECEIVED:" + receivedMsg);
                try {
                    rp.processMessage(receivedMsg);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
        listeningSocket.close();
        System.out.println("Socket closed");
    }
}
